package com.yz.crm.passport.action;


import com.yz.common.exception.ServiceException;

import com.yz.crm.weixin.model.ThirdPartyUser;
import com.yz.crm.weixin.model.token.AuthUserInfoJson;
import com.yz.crm.weixin.service.ThirdPartyUserService;
import com.yz.crm.weixin.service.WechatUserService;
import com.yz.crm.weixin.util.PropertyUtils;
import com.yz.util.Constants;
import com.yz.util.WebUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Date;

/**
 * 页面跳转
 * Created by DOVE on 2015/9/14
 */
@Controller
public class RedirectAction {
    private static final Log log = LogFactory.getLog(RedirectAction.class);

    @Resource
    private WechatUserService wechatUserService;

    @Resource
    private ThirdPartyUserService thirdPartyMemberService;


    @RequestMapping("visitorRedirectService")
    private String visitorRedirectService(HttpServletRequest request,
                                          HttpServletResponse response,
                                          HttpSession session,
                                          String state,
                                          String code) {
        //根据code获取 authUserInfoJson
        AuthUserInfoJson authUserInfoJson = wechatUserService.loadWechatUserInfoByCode(code, PropertyUtils.getValue("wechat.visitor.getinfo.code", ""));
        if (authUserInfoJson == null) {
            //获取微信失败的，不要在返回到原来的指定页面了，防止总是在跳转。
            log.warn("获取openid信息失败");
            return "redirect:/";
        }
        ThirdPartyUser user = thirdPartyMemberService.getInfo(null, authUserInfoJson.getOpenid());
        ThirdPartyUser visitor = new ThirdPartyUser();
        visitor.setOpenId(authUserInfoJson.getOpenid());
        visitor.setNickName(authUserInfoJson.getNickname());
        visitor.setHeadImgUrl(authUserInfoJson.getHeadimgurl());
        visitor.setDelFlag(false);
        try {
            if (user == null) {
                visitor.setCreateDate(new Date());
                thirdPartyMemberService.add(visitor);
            } else {
                visitor.setId(user.getId());
                visitor.setSysUserId(user.getSysUserId());
                visitor.setCreateDate(new Date());
                thirdPartyMemberService.update(visitor);
            }

            WebUtils.addCookie(request, response, Constants.COOKIE_USER_OPENID, visitor.getOpenId(), Constants.COOKIE_MAX_AGE);
            WebUtils.addCookie(request, response, Constants.COOKIE_USER_THIRDPARTY_ID, visitor.getSysUserId().toString(), Constants.COOKIE_MAX_AGE);

        } catch (Exception e) {
            log.info("addCheckOpenIdRepeatThenUpdate 失败");
            return "redirect:/";
        }
        String redirectUrl = WebUtils.getCookie(request, Constants.COOKIE_REDIRECT_URL);
        if (StringUtils.isNotEmpty(redirectUrl)) {
            return "redirect:" + redirectUrl;
        } else {
            return "redirect:/";
        }

    }

    @RequestMapping("userRedirectService")
    private String redirectService(HttpServletRequest request,
                                   HttpServletResponse response,
                                   HttpSession session,
                                   String state,
                                   String code) {
        //根据code获取 authUserInfoJson
        AuthUserInfoJson authUserInfoJson = wechatUserService.loadWechatUserInfoByCode(code, PropertyUtils.getValue("wechat.member.getinfo.code", ""));
        if (authUserInfoJson == null) {
            log.warn("获取openid信息失败");
            return "redirect:/";

        }
        try {
            ThirdPartyUser user = thirdPartyMemberService.getInfo(null, authUserInfoJson.getOpenid());
            ThirdPartyUser visitor = new ThirdPartyUser();
            visitor.setOpenId(authUserInfoJson.getOpenid());
            visitor.setNickName(authUserInfoJson.getNickname());
            visitor.setHeadImgUrl(authUserInfoJson.getHeadimgurl());
            visitor.setDelFlag(false);
            if (user == null) {

                visitor.setCreateDate(new Date());
                thirdPartyMemberService.add(visitor);
            } else {
                visitor.setId(user.getId());
                visitor.setSysUserId(user.getSysUserId());
                visitor.setUpdateDate(new Date());
                thirdPartyMemberService.update(user);
            }
            WebUtils.addCookie(request, response, Constants.COOKIE_USER_OPENID, visitor.getOpenId(), Constants.COOKIE_MAX_AGE);
            WebUtils.addCookie(request, response, Constants.COOKIE_USER_THIRDPARTY_ID, visitor.getSysUserId()==null?"":visitor.getSysUserId()+"", Constants.COOKIE_MAX_AGE);

        } catch (ServiceException e) {
            log.info("addCheckOpenIdRepeatThenUpdate 失败");
            return "redirect:/";
        }

        if (state == null) {
            log.warn("参数错误");
            return "redirect:/";
        }
        return "redirect:" + state;
    }

}
